package com.lzb.newloan;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.moblie.zmxy.antgroup.creditsdk.app.CreditApp;
import com.android.moblie.zmxy.antgroup.creditsdk.app.ICreditListener;
import com.authreal.api.AuthBuilder;
import com.authreal.api.OnResultListener;
import com.authreal.module.BaseResponse;
import com.bqs.crawler.cloud.sdk.BqsCrawlerCloudSDK;
import com.bqs.crawler.cloud.sdk.BqsParams;
import com.bqs.crawler.cloud.sdk.OnLoginResultListener;
import com.bqs.crawler.cloud.sdk.ServiceId;
import com.example.credit.sdk.sp.CreditAuthHelper;
import com.example.credit.sdk.sp.DemoView;
import com.face.bsdk.crypt.Md5;
import com.google.gson.Gson;
import com.lzb.newloan.bqs.AppCacheUtils;
import com.lzb.newloan.bqs.BasPojo;
import com.lzb.newloan.bqs.BasPojo2;
import com.lzb.newloan.bqs.CatLoadingView;
import com.lzb.newloan.bqs.Datas;
import com.lzb.newloan.utils.Config;
import com.lzb.newloan.utils.HttpUtils;
import com.lzb.newloan.view.MyProgressDialog;
import com.lzb.newloan.utils.AlertDialog;
import org.json.JSONException;
import org.json.JSONObject;
import com.lzb.newloan.utils.BaseActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class MyInfoActivity extends BaseActivity implements OnClickListener, OnLoginResultListener,
        DemoView {
    private int rzstatus, isshenfen, islianxi, isjob, ismobile, istaobao, isjd,
            sfzmrz;
    private String realName, cardNo;

    private String mobilephone;
    private ImageView shenfen_msg_img, person_guanxi_img, person_work_img,
            jd_icon, taobao_icon, mobile_icon, zm_icon;
    private TextView person_guanxi_txt, shenfen_msg_txt, person_work_txt,
            jd_txt, taobao_txt, mobile_txt, zm_txt;
    private String userId;
    public String packageSessionId;
    private MyProgressDialog dialog;
    private CatLoadingView loadingView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        initView();
        initData();
    }

    private void initView() {
        SharedPreferences sp = getSharedPreferences("config", 0x0000);
        userId = sp.getString("userid", "");
        // mUserId=userId + "+" + System.currentTimeMillis();
        TextView title_txt_center = (TextView) findViewById(R.id.title_txt_center);
        title_txt_center.setText("我的资料");
        RelativeLayout backpress = (RelativeLayout) findViewById(R.id.backpress);
        backpress.setOnClickListener(this);
        LinearLayout shenfen_msg_linear = (LinearLayout) findViewById(R.id.shenfen_msg_linear);
        shenfen_msg_linear.setOnClickListener(this);
        LinearLayout person_guanxi_linear = (LinearLayout) findViewById(R.id.person_guanxi_linear);
        person_guanxi_linear.setOnClickListener(this);
        LinearLayout person_work_linear = (LinearLayout) findViewById(R.id.person_work_linear);
        person_work_linear.setOnClickListener(this);
        LinearLayout mobile_linear = (LinearLayout) findViewById(R.id.mobile_linear);
        mobile_linear.setOnClickListener(this);
        LinearLayout taobao_linear = (LinearLayout) findViewById(R.id.taobao_linear);
        taobao_linear.setOnClickListener(this);
        LinearLayout jd_linear = (LinearLayout) findViewById(R.id.jd_linear);
        jd_linear.setOnClickListener(this);
        LinearLayout zhima_linear = (LinearLayout) findViewById(R.id.zhima_linear);
        zhima_linear.setOnClickListener(this);
        shenfen_msg_img = (ImageView) findViewById(R.id.shenfen_msg_img);
        person_guanxi_img = (ImageView) findViewById(R.id.person_guanxi_img);
        person_work_img = (ImageView) findViewById(R.id.person_work_img);
        mobile_icon = (ImageView) findViewById(R.id.mobile_icon);
        taobao_icon = (ImageView) findViewById(R.id.taobao_icon);
        jd_icon = (ImageView) findViewById(R.id.jd_icon);
        person_guanxi_txt = (TextView) findViewById(R.id.person_guanxi_txt);
        shenfen_msg_txt = (TextView) findViewById(R.id.shenfen_msg_txt);
        person_work_txt = (TextView) findViewById(R.id.person_work_txt);
        mobile_txt = (TextView) findViewById(R.id.mobile_txt);
        taobao_txt = (TextView) findViewById(R.id.taobao_txt);
        jd_txt = (TextView) findViewById(R.id.jd_txt);
        zm_txt = (TextView) findViewById(R.id.zm_txt);
        zm_icon = (ImageView) findViewById(R.id.zm_icon);

        loadingView = new CatLoadingView(this);
    }

    private void initData() {
        HttpUtils.doPostAsyn(Config.HOME_INIT + "&userid=" + userId, "",mHandler,
                Config.CODE_HOME_INIT);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            String reString = msg.obj.toString();
            switch (msg.what) {
                case Config.CODE_HOME_INIT:
                    Log.e("MainActivity", "result=" + reString);
                    try {
                        JSONObject jsonObject = new JSONObject(reString);
                        mobilephone = jsonObject.getString("mobilephone");
                        realName = jsonObject.getString("rzname");
                        cardNo = jsonObject.getString("rzcard2");
                        AppCacheUtils.getInstance(MyInfoActivity.this).put(Datas.NAME, realName);
                        AppCacheUtils.getInstance(MyInfoActivity.this).put(Datas.CERT_NO, cardNo);
                        AppCacheUtils.getInstance(MyInfoActivity.this).put(Datas.MOBILE, mobilephone);

                        rzstatus = Integer.parseInt(jsonObject
                                .getString("rzstatus"));
                        isshenfen = Integer.parseInt(jsonObject
                                .getString("isshenfen"));
                        isjob = Integer.parseInt(jsonObject.getString("isjob"));
                        istaobao = Integer.parseInt(jsonObject
                                .getString("istaobaoyz"));// istaobaoyz isjingdongyz
                        // isyyshang
                        islianxi = Integer.parseInt(jsonObject
                                .getString("islianxi"));
                        isjd = Integer.parseInt(jsonObject
                                .getString("isjingdongyz"));
                        ismobile = Integer.parseInt(jsonObject
                                .getString("isyyshang"));
                        sfzmrz = Integer.parseInt(jsonObject.getString("sfzmrz"));
                        if (isshenfen == 1) {
                            shenfen_msg_txt.setText("已认证");
                            shenfen_msg_txt.setTextColor(getResources().getColor(
                                    R.color.new_red));
                        }

                        // Toast.makeText(MyInfoActivity.this, "身份证+++"+isshenfen,
                        // Toast.LENGTH_LONG)
                        // .show();

                        if (islianxi == 1) {
                            person_guanxi_txt.setText("已认证");
                            person_guanxi_txt.setTextColor(getResources().getColor(
                                    R.color.new_red));
                        }
                        if (isjob == 1) {
                            person_work_txt.setText("已认证");
                            person_work_txt.setTextColor(getResources().getColor(
                                    R.color.new_red));
                        }
                        if (isjd == 1) {
                            jd_txt.setTextColor(getResources().getColor(
                                    R.color.new_red));
                            jd_txt.setText("已认证");
                            //
                        }
                        if (ismobile == 1) {
                            mobile_txt.setText("已认证");
                            mobile_txt.setTextColor(getResources().getColor(
                                    R.color.new_red));
                        }
                        if (istaobao == 1) {
                            taobao_txt.setText("已认证");
                            taobao_txt.setTextColor(getResources().getColor(
                                    R.color.new_red));
                        }
                        if (sfzmrz == 1) {
                            zm_txt.setText("已认证");
                            zm_txt.setTextColor(getResources().getColor(
                                    R.color.new_red));
                        }
                    } catch (JSONException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    // if (dialog != null) {
                    // dialog.dismiss();
                    // }
                    //
                    System.out.println("+hrl+" + isshenfen);

                    break;
                case Config.CODE_URL_ERROR:
                    Toast.makeText(MyInfoActivity.this, "url错误", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case Config.CODE_NET_ERROR:
                    Toast.makeText(MyInfoActivity.this, "网络错误", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case Config.CODE_AUTHMOBILE:
                    String result = msg.obj.toString();
                    try {
                        JSONObject json = new JSONObject(result);
                        int error = json.getInt("error");
                        if(error==2){
                            initData();
                            Toast.makeText(MyInfoActivity.this, "运营商授权成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(MyInfoActivity.this, json.getString("msg"),
                                    Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        Toast.makeText(MyInfoActivity.this, "数据解析错误",
                                Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                    break;
                case Config.CODE_AUTHTB:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        int error = json.getInt("error");
                        if(error==2){
                            initData();
                            Toast.makeText(MyInfoActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(MyInfoActivity.this, json.getString("msg"),
                                    Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        Toast.makeText(MyInfoActivity.this, "数据解析错误",
                                Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }

                    break;
//
                case Config.CODE_ZMSTART:
                    try {
                        JSONObject json = new JSONObject(reString);
                        if (json.optString("resultCode").equals("BQS000")) {
                            // Intent intent = new Intent(MyInfoActivity.this,
                            // WebviewActivity.class);
                            // intent.putExtra("url", json.getString("url"));
                            // startActivity(intent);
//                            String params = json.getString("params");
//                            String appId = json.getString("app_id");
//                            String sign = json.getString("sign");
//                            zmAuth(params, appId, sign);

                            JSONObject resultData = json.getJSONObject("resultData");
                            String authInfoUrl=  resultData.getString("authInfoUrl");
                            Intent intentZm = new Intent(MyInfoActivity.this, WebviewActivity.class);
                            intentZm.putExtra("title", "芝麻认证");
                            intentZm.putExtra("url", authInfoUrl);
                            startActivity(intentZm);
                            finish();
                        } else {
                            Toast.makeText(MyInfoActivity.this,
                                    json.getString("resultDesc"), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case Config.CODE_ZMEND:
                    try {
                        JSONObject json = new JSONObject(reString);
                        if (json.getInt("error") == 0) {
                            HttpUtils.doPostAsyn(Config.HOME_INIT + "&userid=" + userId,"", mHandler,
                                    Config.CODE_HOME_INIT);
                            sfzmrz = 1;
                            zm_txt.setText("已认证");
                            zm_txt.setTextColor(getResources().getColor(
                                    R.color.new_red));
                        } else {
                            Toast.makeText(MyInfoActivity.this,
                                    json.getString("msg"), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backpress:
                Intent intents = new Intent(MyInfoActivity.this,
                        IndexActivity.class);
                intents.putExtra("id", 1);
                startActivity(intents);
                finish();
                break;
            case R.id.shenfen_msg_linear:
                if (rzstatus!=1) {//请绑定银行卡
                    Intent intent = new Intent(MyInfoActivity.this,
                            BindCard2Activity.class);
                    startActivity(intent);
                    finish();
                    return;
                }
                System.out.println("+shenfen+" + isshenfen);
                if (isshenfen != 1) {// 请填写身份信息 （人脸识别）
                    ActivityCompat.requestPermissions(MyInfoActivity.this,
                            new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            1);
                    mSAocrLiveness();

                } else if (isshenfen == 1) {
                    setDialog("您已经提交了身份信息，无需再次提交");
                }
                break;
            case R.id.person_guanxi_linear:

                if (islianxi != 1) {// 请填写个人信息
                    ActivityCompat.requestPermissions(MyInfoActivity.this,
                            new String[]{Manifest.permission.READ_CONTACTS,Manifest.permission.READ_PHONE_STATE},
                            1);
                    Intent intent = new Intent(MyInfoActivity.this,
                            RelationInfoActivity.class);
                    startActivity(intent);

                } else if (islianxi == 1) {
                    setDialog("您已经提交了人际信息，无需再次提交");
                }
                break;
            case R.id.person_work_linear:
                if (isjob != 1) {
                    Intent intent = new Intent(MyInfoActivity.this,
                            WorkInfoActivity.class);
                    startActivity(intent);
                } else if (isjob == 1) {
                    setDialog("您已经提交了工作信息，无需再次提交");
                }
                break;
            case R.id.mobile_linear:// 手机运营商
                if (rzstatus != 1) {// 请绑定银行卡
                    Intent intent = new Intent(MyInfoActivity.this,
                            BindCard2Activity.class);
                    startActivity(intent);
                    finish();
                    return;
                }
                if (islianxi != 1 || isjob != 1 || isshenfen != 1) {
                    setDialog("请先绑定基本信息");
                    return;
                }
                if (ismobile == 1) {
                    setDialog("您已认证了手机运营商，无需再次认证！");
                    return;
                }

                startPage(0);

//                startAuth(MxParam.PARAM_FUNCTION_CARRIER);
                break;
            case R.id.taobao_linear:
                if (rzstatus != 1) {// 请绑定银行卡
                    Intent intenttb = new Intent(MyInfoActivity.this,
                            BindCard2Activity.class);
                    startActivity(intenttb);
                    finish();
                    return;
                }
                if (islianxi != 1 || isjob != 1 || isshenfen != 1) {
                    setDialog("请先绑定基本信息");
                    return;
                }
                if (istaobao == 1) {
                    setDialog("您已认证了淘宝，无需再次认证！");
                    return;
                }

                startPage(1);
                break;
            case R.id.jd_linear:
                if (rzstatus != 1) {// 请绑定银行卡
                    Intent intentjd = new Intent(MyInfoActivity.this,
                            BindCard2Activity.class);
                    startActivity(intentjd);
                    finish();
                    return;
                }
                if (islianxi != 1 || isjob != 1 || isshenfen != 1) {
                    setDialog("请先绑定基本信息");
                    return;
                }
                if (isjd == 1) {
                    setDialog("您已认证了京东，无需再次认证！");
                    return;
                }
                startPage(2);
                break;

            case R.id.zhima_linear:

                if (rzstatus != 1) {// 请绑定银行卡
                    Intent intentzm = new Intent(MyInfoActivity.this,
                            BindCard2Activity.class);
                    startActivity(intentzm);
                    finish();
                    return;
                }
                if (islianxi != 1 || isjob != 1 || isshenfen != 1) {
                    setDialog("请先绑定基本信息");
                    return;
                }
                if (sfzmrz == 1) {
                    setDialog("您已认证了芝麻，无需再次认证！");
                    return;
                }

                // zmAuth();

                BasPojo pojo = new BasPojo();
                BasPojo2 pojo2 = new BasPojo2();
                pojo2.setName(realName);
                pojo2.setCertNo(cardNo);
                pojo2.setChannel("app");
                pojo2.setIdentityType("2");
                pojo2.setCallbackUrl(Config.ZM_NOTIF_URL+"&userid="+userId);
                pojo.setExtParam(pojo2);
                pojo.setVerifyKey(Datas.VERIFY_KEY);
                pojo.setPartnerId(Datas.PARTNET_ID);
                pojo.setLinkedMerchantId("2088721130432795");
                pojo.setProductId("102001");
                String re = JSON.toJSONString(pojo);
                HttpUtils.doPostAsyn("https://api.baiqishi.com/credit/zhima/search" ,re, mHandler, Config.CODE_ZMSTART);

//



                break;
            default:
                break;
        }
    }


    private void startPage(int type) {
        BqsParams params = new BqsParams();
        params.setName(realName);
        params.setCertNo(cardNo);
        params.setMobile(mobilephone);
        params.setPartnerId(Datas.PARTNET_ID);
        params.setThemeColor(getResources().getColor(R.color.blue));
        params.setForeColor(Color.WHITE);
        BqsCrawlerCloudSDK.setParams(params);

        BqsCrawlerCloudSDK.setFromActivity(this);
        BqsCrawlerCloudSDK.setOnLoginResultListener(this);

        switch (type){
            case 0://运营商
                BqsCrawlerCloudSDK.loginMno();
                break;
            case 1://淘宝
                BqsCrawlerCloudSDK.loginTaobao();
                break;
            case 2://京东
                BqsCrawlerCloudSDK.loginJD();
                break;


        }


    }



    /**
     * 接收SDK的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out
                .println("返回結果" + requestCode + "+" + resultCode + "+" + data);

        switch (requestCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK

            case 8001:
                CreditApp.onActivityResult(requestCode, resultCode, data);
                break;
            default:
                break;
        }
    }

    // S-A(OCR+活体)
    public void mSAocrLiveness() {
        AuthBuilder authBuilder = getAuthBuilder();

        authBuilder.isShowConfirm(true);// 2016/12/28 OCR之后需要确认身份证识别信息
        authBuilder.setPackageCode("TC008");
        // authBuilder.setPackageCode(getCodeS());// 如果有的话需要设置,可不设置

        authBuilder.ocrLiveness(this, Config.SF_NOTIFY_URL);

    }

    private AuthBuilder getAuthBuilder() {
        // SharedPreferences sp = getSharedPreferences("config", 0x0000);
        // String UserId = sp.getString("userid", "");
        /** 测试环境 */
        String partner_order_id = userId + "&" + System.currentTimeMillis(); // 商户订单号;
        String pubKey = "cf755e26-bcf2-4ebb-840e-30387807ea8f"; // 商户号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyyMMddHHmmss");
        String sign_time = simpleDateFormat.format(new Date());
        String security_key = "7caa0671-9d30-470b-9d13-792c817e1506"; // 商户密钥

        String singStr = "pub_key=" + pubKey + "|partner_order_id="
                + partner_order_id + "|sign_time=" + sign_time
                + "|security_key=" + security_key;

        Log.d("MainActivity", singStr);

        String sign = Md5.encrypt(singStr);

        OnResultListener listener = new OnResultListener() {
            @Override
            public void onResult(int op_type, String result) {

                BaseResponse response = new Gson().fromJson(result,
                        BaseResponse.class);
                if (response != null
                        && !TextUtils.isEmpty(response.package_session_id)) {
                    packageSessionId = response.package_session_id;
                }
                try {
                    switch (op_type){
                        case AuthBuilder.OPTION_ERROR://流程终端异常----取消验证
                            Toast.makeText(getApplicationContext(), "身份识别失败，请重试",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case AuthBuilder. OPTION_LIVENESS: //活体检测结果回调 result+="活体检测";
//                            Toast.makeText(getApplicationContext(), "OCR"+result,
//                                    Toast.LENGTH_SHORT).show();
                            JSONObject object = new JSONObject(result);
                            int code = object.getInt("ret_code");
                            if (code == 000000) {
                                isshenfen = 1;
                                shenfen_msg_txt.setText("已认证");
                                shenfen_msg_txt.setTextColor(getResources().getColor(
                                        R.color.new_red));

                                Toast.makeText(getApplicationContext(), "识别成功",
                                        Toast.LENGTH_SHORT).show();
                                System.out.println("+code+" + isshenfen);
                            }
                            break;
                        case AuthBuilder.OPTION_OCR: //身份证结果回调 身份证扫描结果result="OCR结果";身份证扫描成功会弹出身份识别成功

//                                Toast.makeText(getApplicationContext(), "OCR结果" + result,
//                                        Toast.LENGTH_SHORT).show();
//
                            break;
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("+结果返回+" + result);

            }

        };
        return new AuthBuilder(partner_order_id, pubKey, sign_time, sign,
                listener);
    }

    private void zmAuth(String params, String appId, String sign) {
        // TODO Auto-generated method stub
        // 测试数据，此部分数据，请由商户服务端生成下发，具体见开放平台商户对接文档
        // 请注意params、sign为encode过后的数据
        // String params =
        // "IsFyG77jip6mJt%2BgyeC8i4knR16LUEJXr9h0Tt7cp%2Bt6gFW9uQem599fnJGFEI0wHJCd84yQ8y89nBV5%2BKdLqEgwE7xRLrWj6fCbYvRnIjFIDthShR5nS1PY4W2abNxq%2BJTp%2BT2OJa9NOLIZq9HXOZg8%2BSVgTbkAt5dmrjmhnTdBCvV3zVsO7p83YN9js8ESPCZyWCNgyWOIPPeSePrBsZEXCs2ebxwQGN62%2FdeqaW1S9PKKEg7e8i%2F6PK2xZYjLFfNydoS1gqA%2BGDkhVeCsN6NZyWffotS0QWA9j9PXSN6nYN8HNIAma5%2BBq%2FbKDsxK0Af2CXg%2B3FJ3ArnnlHr6iLI96m6AsZYZlYcYFwbE25KZysohn5SqsVAF2AZriSEHEpiak9k6AIOduVmrlwuI6sdP%2FqoWM1oEgqnEV%2Faiz7ydODatVe5CC6pdJxP7ZxbyzOyMAB7um3uYjPQb0LTOsvOsRgCMQAPH8%2FJrMZvrHyv0q3C9NjnNQKDYlATYXJCa";
        // String appId = "1002180";
        // String sign =
        // "LpalhM1PJPKudoUCSZDBslOCMCG%2F8KIODWzby%2FxEaNV%2F3oAk5FGTXN4XTXDXf6qaYo6tsRmGjCvR%2FCr14KLwNb%2B7lIkVwSplGVV1b6ngQeEQPNjWrpyUolyR%2BsZ368vaJ%2BXJBh3jLg%2FyRGDD%2FNg6cNuQgt1JggKVZIed6Zmk%2FUg%3D";

        // extParams参数可以放置一些额外的参数，例如当biz_params参数忘记组织auth_code参数时，可以通过extParams参数带入auth_code。
        // 不过建议auth_code参数组织到biz_params里面进行加密加签。
        Map<String, String> extParams = new HashMap<>();
        // extParams.put("auth_code", "M_FACE");
        extParams.put("state", userId);

        try {
            // 请求授权
            CreditAuthHelper.creditAuth(MyInfoActivity.this, appId, params,
                    sign, extParams, new ICreditListener() {
                        private String paramsHttp;
                        private String signHttp;

                        @Override
                        public void onComplete(Bundle result) {
                            // toast message
                            MyInfoActivity.this.toastMessage("授权成功");
                            // 从result中获取params参数,然后解析params数据,可以获取open_id。

                            if (result != null) {
                                Set<String> keys = result.keySet();
                                for (String key : keys) {
                                    if (key.equals("params")) {
                                        paramsHttp = result.getString(key);
                                    }
                                    if (key.equals("sign")) {
                                        signHttp = result.getString(key);
                                    }
                                    Log.d("ZHIMA_DemoActivity", key + " = "
                                            + result.getString(key));
                                }
                            }
                            try {
                                paramsHttp = URLDecoder.decode(paramsHttp,
                                        "UTF-8");
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            try {
                                signHttp = URLDecoder.decode(signHttp, "UTF-8");
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                            String params = "&params=" + paramsHttp + "&sign="
                                    + signHttp;
                            checkdata(params);
                        }

                        @Override
                        public void onError(Bundle result) {
                            // toast message
                            MyInfoActivity.this.toastMessage("授权错误");
                            Log.d("ZHIMA_DemoActivity",
                                    "DemoPresenterImpl.doCreditAuthRequest.onError.");
                        }

                        @Override
                        public void onCancel() {
                            // toast message
                            MyInfoActivity.this.toastMessage("授权失败");
                            Log.d("ZHIMA_DemoActivity",
                                    "DemoPresenterImpl.doCreditAuthRequest.onCancel.");
                        }
                    });
        } catch (Exception e) {
            Log.e("ZHIMA_DemoActivity",
                    "DemoPresenterImpl.doCreditAuthRequest.exception="
                            + e.toString());
        }
    }

    private void checkdata(final String param) {
        // 启动子线程异步加载数据
        new Thread() {

            @Override
            public void run() {

                Message msg = Message.obtain();
                PrintWriter out = null;
                BufferedReader in = null;
                String result = "";
                try {
                    URL realUrl = new URL(Config.ZMEND_CORD);
                    // 打开和URL之间的连接
                    HttpURLConnection conn = (HttpURLConnection) realUrl
                            .openConnection();
                    // 设置通用的请求属性
                    conn.setRequestProperty("accept", "*/*");
                    conn.setRequestProperty("connection", "Keep-Alive");
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type",
                            "application/x-www-form-urlencoded");
                    conn.setRequestProperty("charset", "utf-8");
                    conn.setUseCaches(false);
                    // 发送POST请求必须设置如下两行
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);
                    if (param != null && !param.trim().equals("")) {
                        // 获取URLConnection对象对应的输出流
                        out = new PrintWriter(conn.getOutputStream());
                        // 发送请求参数
                        out.print(param);
                        // flush输出流的缓冲
                        out.flush();
                    }
                    // 定义BufferedReader输入流来读取URL的响应
                    in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String line;
                    while ((line = in.readLine()) != null) {
                        result += line;
                    }
                    msg.what = Config.CODE_ZMEND;
                    System.out.println(result);
                    // } else {
                    // msg.what = Config.CODE_URL_ERROR;
                    // }
                } catch (Exception e) {
                    // 网络错误异常
                    msg.what = Config.CODE_NET_ERROR;
                    e.printStackTrace();
                }
                // 使用finally块来关闭输出流、输入流
                finally {
                    try {
                        if (out != null) {
                            out.close();
                        }
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException ex) {
                        // 网络错误异常
                        msg.what = Config.CODE_NET_ERROR;
                        ex.printStackTrace();
                    }
                }
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }.start();
    }

    @Override
    public void toastMessage(final String msg) {
        // check context
        if (isFinishing() || TextUtils.isEmpty(msg)) {
            return;
        }
        // toast message
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MyInfoActivity.this, msg, Toast.LENGTH_LONG)
                        .show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        finish();
        super.onBackPressed();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Intent intents = new Intent(MyInfoActivity.this,
                    IndexActivity.class);
            intents.putExtra("id", 1);
            startActivity(intents);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setDialog(String Message) {
        new AlertDialog(MyInfoActivity.this).builder().setMsg(Message)
                .setNegativeButton("确定", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();
    }

    @Override
    public void processMessage(Message message) {
        // TODO Auto-generated method stub

    }


    @Override
    public void onLoginSuccess(int serviceId) {
        if (serviceId == ServiceId.JD_SERVICE_ID) {
            HttpUtils.doPostAsyn(Config.AUTHJD_CORD
                            + "&userid=" + userId, "",mHandler,
                    Config.CODE_AUTHTB);
        } else if (serviceId == ServiceId.TB_SERVICE_ID) {
            HttpUtils.doPostAsyn(Config.AUTHTAOBAO_CORD+"&userid=" + userId , "",mHandler,
                    Config.CODE_AUTHTB);
        }else if(serviceId == ServiceId.MNO_SERVICE_ID){
            HttpUtils.doPostAsyn(Config.AUTHMOBILE_CORD
                            + "&userid=" + userId,"", mHandler,
                    Config.CODE_AUTHMOBILE);
        }

//        Toast.makeText(this,""+serviceId,Toast.LENGTH_LONG).show();
        System.out.println("授权成功 serviceId=" + serviceId);
    }

    @Override
    public void onLoginFailure(String resultCode, String resultDesc, int serviceId) {
        System.out.println("onLoginFailure resultCode=" + resultCode +" ,resultDesc=" + resultDesc +",  serviceId=" + serviceId);
    }
}
